use crate::updateinfo::{Asset, UpdateInfo};
use anyhow::anyhow;
use updateinfo::Infos;

pub mod updateinfo;

pub async fn new(repo: &str, version: &str) -> Result<Asset, anyhow::Error> {
    let a = httpget(repo).await?;
    let b = upor(a.last().unwrap().clone(), version)?;
    Ok(b)
}

async fn httpget(repo: &str) -> Result<Infos, anyhow::Error> {
    let cli = reqwest::Client::new();
    let api = format!("https://gitee.com/api/v5/repos/{repo}/releases");
    let res = cli.get(api)
        .timeout(std::time::Duration::from_secs(30))
        .header("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0")
        .send()
        .await?
        .json::<Infos>()
        .await?;
    if !res.is_empty() {
        Ok(res)
    } else {
        eprintln!("没有软件");
        Err(anyhow::anyhow!("error空"))
    }
}

/// 是否更新
fn upor(info: UpdateInfo, version: &str) -> Result<Asset, anyhow::Error> {
    let a = info.tag_name.clone();
    let re = regex::Regex::new(r"v(\d)\.(\d)\.(\d)")?;
    let new_vsesion = re.captures(&*a).unwrap();
    let old_vsesion = re.captures(version).unwrap();
    let new = new_vsesion.get(1).unwrap().as_str().parse::<u32>()? * 100
        + new_vsesion.get(2).unwrap().as_str().parse::<u32>()? * 10
        + new_vsesion.get(3).unwrap().as_str().parse::<u32>()?;
    let old = old_vsesion.get(1).unwrap().as_str().parse::<u32>()? * 100
        + old_vsesion.get(2).unwrap().as_str().parse::<u32>()? * 10
        + old_vsesion.get(3).unwrap().as_str().parse::<u32>()?;
    println!("最新->{} 当前版本->{}", new, old);
    if new > old {
        // println!("update");
        Ok(info.assets.first().unwrap().clone())
    } else {
        Err(anyhow!("无需更新"))
    }
}
